package com.whf.android.jar.web;

import android.os.Bundle;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebViewClient;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.whf.android.jar.app.Latte;
import com.whf.android.jar.base.delegate.IPageLoadListener;
import com.whf.android.jar.web.client.WebChromeClientImpl;
import com.whf.android.jar.web.client.WebLongClickImpl;
import com.whf.android.jar.web.client.WebViewClientImpl;
import com.whf.android.jar.web.downLoad.DownLoadWebView;
import com.whf.android.jar.web.initializer.IWebViewInitializer;
import com.whf.android.jar.web.news.NewsWebView;
import com.whf.android.jar.web.route.Router;

import org.jetbrains.annotations.NotNull;


/**
 * 具体实现的webView布局
 * 布局加 FragmentContainerView
 * 然后 final WebDelegateImpl delegate = WebDelegateImpl.create(url);
 * delegate.setPageLoadListener(this);
 * loadRootFragment(id,delegate);
 *
 * @author hf
 * @version 1.0.5
 */
public class WebDelegateImpl extends WebDelegate {

    private IPageLoadListener mIPageLoadListener = null;

    protected WebDelegateImpl(String url, boolean handleWebUrl) {
        super(url, handleWebUrl);
    }

    @NotNull
    public static WebDelegateImpl create(String url) {
        return new WebDelegateImpl(url, true);
    }

    @NotNull
    public static WebDelegateImpl create(String url, boolean handleWebUrl) {
        return new WebDelegateImpl(url, handleWebUrl);
    }

    @Override
    public Object setLayout() {
        return getWebView();
    }

    /**
     * @param listener:设置加载进度条
     */
    public void setPageLoadListener(IPageLoadListener listener) {
        this.mIPageLoadListener = listener;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
        if (getUrl() != null) {
            //用原生的方式模拟Web跳转并进行页面加载
            Router.getInstance().loadPage(this, getUrl());
        }
    }

    @Override
    public IWebViewInitializer setInitializer() {
        return this;
    }

    @Override
    public NewsWebView initWebView(NewsWebView webView) {
        return new WebViewInitializer().createWebView(webView);
    }

    @Override
    public WebViewClient initWebViewClient() {
        final WebViewClientImpl client = new WebViewClientImpl(this);
        client.setPageLoadListener(mIPageLoadListener);
        client.setHandleWebUrl(isHandleWebUrl());
        return client;
    }

    @Override
    public WebChromeClient initWebChromeClient() {
        return new WebChromeClientImpl();
    }

    @Override
    public DownloadListener initDownloadListener() {
        return new DownLoadWebView(Latte.getActivity());
    }

    @Override
    public WebLongClickImpl initWebLongListener() {
        return new WebLongClickImpl();
    }

}
